<template>
  <!-- <div id="recordDownload" >
    <el-dialog :title="title" v-if="showDialog"  width="45rem" :append-to-body="true" :close-on-click-modal="false" :visible.sync="showDialog" :destroy-on-close="true" @close="close()" center>
      <el-row>
        <el-col :span="18" style="padding-top: 7px;">
          <el-progress :percentage="percentage"></el-progress>
        </el-col>
        <el-col :span="6" >
          <el-button icon="el-icon-download" v-if="downloadFile" size="mini" title="点击下载" @click="downloadFileClientEvent()">下载</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div> -->
  <div class="load-tips" v-show="showDialog">
    <div class="load-head">
      <div class="load-title">下载任务</div>
      <!-- <div class="load-icon" @click="handleClose">隐藏</div> -->
    </div>
    <div class="load-content">
      <a-progress :percent="percentage" strokeColor="#52C41A" trailColor="#dddddd" />
    </div>
  </div>
</template>

<script>
  import { api as gbRecordApi } from '/@/api/wvp/gb_record.js';

  export default {
    name: 'recordDownload',
    created() {
      window.addEventListener('beforeunload', this.stopDownloadRecord);
    },
    data() {
      return {
        title: '下载中...',
        deviceId: '',
        channelId: '',
        app: '',
        stream: '',
        mediaServerId: '',
        showDialog: false,
        scale: 1,
        percentage: 0.0,
        streamInfo: null,
        taskId: null,
        getProgressRun: false,
        timer: null,
        downloadFile: null,
      };
    },
    methods: {
      openDialog: function (url, streamInfo) {
        const urlList = url.split('/');
        const { app, stream, mediaServerId } = streamInfo;
        this.deviceId = urlList[0];
        this.channelId = urlList[1];
        this.app = app;
        this.stream = stream;
        this.mediaServerId = mediaServerId;
        this.showDialog = true;
        this.getProgressRun = true;
        this.percentage = 0.0;
        this.getProgressTimer();
      },
      getProgressTimer: function () {
        if (!this.getProgressRun) {
          return;
        }
        if (this.percentage == 100) {
          return;
        }
        setTimeout(() => {
          if (!this.showDialog) return;
          this.getProgress(this.getProgressTimer());
        }, 5000);
      },
      getProgress: function (callback) {
        gbRecordApi
          .getProgress({
            deviceId: this.deviceId,
            channelId: this.channelId,
            stream: this.stream,
          })
          .then((res) => {
            if (res.code === 0) {
              this.streamInfo = res.data;
              if (parseFloat(res.progress) == 1) {
                this.percentage = 100;
              } else {
                this.percentage = (parseFloat(res.data.progress) * 100).toFixed(1);
              }
              if (this.streamInfo.downLoadFilePath) {
                if (location.protocol === 'https:') {
                  this.downloadFile = this.streamInfo.downLoadFilePath.httpsPath;
                } else {
                  this.downloadFile = this.streamInfo.downLoadFilePath.httpPath;
                }
                this.getProgressRun = false;
                this.showDialog = false;
                this.downloadFileClientEvent();
              }
              if (callback) callback();
            } else {
              this.$message({
                showClose: true,
                message: res.msg,
                type: 'error',
              });
              this.close();
            }
          })
          .catch((e) => {
            console.log(e);
          });
      },
      close: function () {
        if (this.streamInfo.progress < 1) {
          this.stopDownloadRecord();
        }

        if (this.timer !== null) {
          window.clearTimeout(this.timer);
          this.timer = null;
        }
        this.showDialog = false;
        this.getProgressRun = false;
      },
      gbScale: function (scale) {
        this.scale = scale;
      },

      stopDownloadRecord: function (callback) {
        gbRecordApi
          .stopDownload({
            deviceId: this.deviceId,
            channelId: this.channelId,
            stream: this.stream,
          })
          .then((res) => {
            if (callback) callback(res);
          });
      },
      old_downloadFileClientEvent() {
        // window.open(this.downloadFile )
        let x = new XMLHttpRequest();
        const downloadFileUrl = this.downloadFile.replace(
          /^http:\/\/192\.168\.1\.111:80\/index\/api\/downloadFile\?file_path=F:\/xnr\/zlk\/www\/record\/rtp/,
          '/wvpFileApi/record/rtp'
        );
        x.open('GET', downloadFileUrl, true);
        x.responseType = 'blob';
        x.onload = (e) => {
          let url = window.URL.createObjectURL(x.response);
          let a = document.createElement('a');
          a.href = url;
          a.download = this.deviceId + '-' + this.channelId + '.mp4';
          a.click();
          this.handleClose();
        };
        x.send();
      },
      downloadFileClientEvent() {
        const downloadFileUrl = this.downloadFile.replace(
          /^http:\/\/192\.168\.1\.111:80\/index\/api\/downloadFile\?file_path=F:\/xnr\/zlk\/www\/record\/rtp/,
          '/wvpFileApi/record/rtp'
        );
        const link = document.createElement('a');
        link.href = downloadFileUrl;
        link.download = downloadFileUrl;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      handleClose() {
        this.showDialog = false;
      },
    },
    unmounted() {
      window.removeEventListener('beforeunload', this.stopDownloadRecord);
    },
  };
</script>

<style scoepd lang="less">
  .load-tips {
    position: fixed;
    z-index: 10000;
    bottom: 15px;
    right: 15px;
    border-radius: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    box-sizing: border-box;
    background-color: #1d77c4bb;
    width: 200px;
    padding: 10px 10px;
    border: 2px solid #2a82e4;
    .load-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #eee;
      .load-icon {
        cursor: pointer;
        user-select: none;
        text-decoration: underline;
        font-size: 12px;
      }
    }
    .load-content {
      margin-top: 10px;
      .ant-progress-text {
        color: #eee;
      }
    }
  }
</style>
